import axios from "axios";
import { Notify, Dialog } from "vant";

const service = axios.create({
  timeout: 5000,
});

// Request interceptors
service.interceptors.request.use(
  (config) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    if (localStorage.getItem("customer-token")) {
      config.headers["token"] = localStorage.getItem("customer-token");
    }
    if (localStorage.getItem("manager-token")) {
      config.headers["Authorization"] =
        "Bearer " + localStorage.getItem("manager-token");
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      Notify(res.msg || "Error");
      if (res.code === 207 || res.code === 401) {
        Dialog.alert({
          message: "请登录后访问",
        }).then(() => {
          localStorage.removeItem("customer-token");
          localStorage.removeItem("manager-token");
          window.location.href = "/";
        });
      }
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return response.data;
    }
  },
  (error) => {
    Notify(error.message);
    return Promise.reject(error);
  }
);

export default service;
